package com.killer.config;

import com.alibaba.druid.util.StringUtils;
import com.killer.pojo.Configuration;
import com.killer.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    //接卸mapper.xml，生成MappedStatement对象，并封装进configuration对象中
    public void parse(InputStream inputStream) throws DocumentException, ClassNotFoundException {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(inputStream);
        Element rootElement = document.getRootElement();
        //解析所有select标签
        parse(rootElement,"select");
        //解析所有insert标签
        parse(rootElement,"insert");
        //解析所有update标签
        parse(rootElement,"update");
        //解析所有delete标签
        parse(rootElement,"delete");
    }

    private void parse(Element rootElement, String opType) throws ClassNotFoundException {
        String nameSpace = rootElement.attributeValue("namespace");
        List<Element> elementList = rootElement.selectNodes("//" + opType);
        for (Element element : elementList) {
            String id = element.attributeValue("id");
            String sql=element.getTextTrim();
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            configuration.getMappedStatementMap().put(nameSpace+"."+id,new MappedStatement(id,sql,getClass(parameterType),getClass(resultType),opType));
        }
    }

    private Class<?> getClass(String classType) throws ClassNotFoundException {
        if (StringUtils.isEmpty(classType)) {
            return null;
        }
        return Class.forName(classType);
    }

}
